import React, { memo, useState, useEffect } from 'react'
import { Card } from 'antd'

const Storage = memo(() => {
    const [name, setName] = useState('');
    const [newVal, setNewVal] = useState('');
    const [oldVal, setOldVal] = useState('');

    const handle = (event: any) => {
        console.log(event);
        setName(event.key);
        setNewVal(event.newValue);
        setOldVal(event.oldValue);
    }

    useEffect(() => {
        window.addEventListener('storage', handle);

        return () => {
            window.removeEventListener('storage', handle)
        }
    }, [])

    return (
        <Card title="监听Storage变化">
            <p>被修改的键名：<span style={{ color: 'red' }}>{name}</span></p>
            <p>对应的新值：<span style={{ color: 'red' }}>{newVal}</span></p>
            <p>对应的旧值：<span style={{ color: 'red' }}>{oldVal}</span></p>
        </Card>
    )
})

export default Storage